package com.example.permission.service.impl;

import com.example.common.enetiy.AccessLog;
import com.example.common.enetiy.User;
import com.example.common.mapper.AccessLogMapper;
import com.example.common.service.UserService;
import com.example.permission.model.resp.AccessLogVO;
import com.example.permission.service.AccessLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Map;

/**
 * @author qwer3
 * @version 1.0.0
 * @create 2025/11/22 20:11
 */
@Service
@RequiredArgsConstructor
public class AccessLogServiceImpl implements AccessLogService {
    private final AccessLogMapper accessLogMapper;
    private final UserService userService;

    @Override
    public List<AccessLogVO> listAccessLog() {
        Map<String, User> userMap = userService.getUserMap();
        List<AccessLog> accessLogs = accessLogMapper.listAccessLog();
        return accessLogs.stream()
                .filter(accessLog ->
                        accessLog.getIp() != null &&
                                !accessLog.getIp().equals("0:0:0:0:0:0:0:1") &&
                                accessLog.getTimestamp() != null
                )
                .map(accessLog -> AccessLogVO.builder()
                        .username( userMap.get(accessLog.getUserId()).getUsername())
                        .loginTime(LocalDateTime.ofInstant(
                                Instant.ofEpochMilli(accessLog.getTimestamp()),
                                ZoneId.of("Asia/Shanghai")
                        ))
                        .ipAddress(accessLog.getIp())
                        .location("-")
                        .device(accessLog.getDeviceType())
                        .os(accessLog.getOperatingSystem())
                        .browser(accessLog.getBrowser())
                        .status("在线")
                        .build()
                )
                .toList();
    }
}
